<template>
  <div>
    <!--查询区域-->
    <div class="jeecg-basic-table-form-container">
      <a-form ref="formRef" @keyup.enter.native="searchQuery" :model="queryParam" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-row :gutter="24">
          <a-col :lg="8">
            <a-form-item label="小说名" name="bookName">
              <a-input placeholder="请输入小说名" v-model:value="queryParam.bookName" />
            </a-form-item>
          </a-col>
          <a-col :lg="8">
            <a-form-item label="作者名" name="authorName">
              <a-input placeholder="请输入作者名" v-model:value="queryParam.authorName" />
            </a-form-item>
          </a-col>
          <a-col :lg="8">
            <a-form-item label="最新章节更新时间：" name="lastIndexUpdateTime">
              <a-date-picker
                class="mt-global-time"
                value-format="YYYY-MM-DD"
                placeholder="请选择时间"
                v-model:value="queryParam.lastIndexUpdateTime"
              />
            </a-form-item>
          </a-col>
          <a-col :lg="8">
            <a-form-item label="入库时间：" name="createTime">
              <a-date-picker class="mt-global-time" value-format="YYYY-MM-DD" placeholder="请选择时间" v-model:value="queryParam.createTime" />
            </a-form-item>
          </a-col>
          <a-col :lg="8">
            <a-form-item label="分类名：" name="catName">
              <a-select v-model:value="queryParam.catName" placeholder="请选择分类名" allowClear showSearch>
                <a-select-option :value="item" v-for="(item, index) in categoryList" :key="index">{{ item }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :lg="8">
            <a-form-item label="是否自动采集：" name="isAutoCollection">
              <a-select v-model:value="queryParam.isAutoCollection" placeholder="请选择是否自动采集" allowClear>
                <a-select-option :value="0">否</a-select-option>
                <a-select-option :value="1">是</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :lg="8">
            <a-form-item label="采集状态：" name="collectionStatus">
              <a-select v-model:value="queryParam.collectionStatus" placeholder="请选择采集状态" allowClear @change="changeCollectionStatus">
                <a-select-option :value="0">失败</a-select-option>
                <a-select-option :value="1">成功</a-select-option>
                <a-select-option :value="2">进行中</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :lg="8">
            <a-form-item label="书籍状态：" name="bookStatus">
              <a-select v-model:value="queryParam.bookStatus" placeholder="请选择书籍状态" allowClear>
                <a-select-option :value="0">连载中</a-select-option>
                <a-select-option :value="1">已完结</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>

          <a-col :lg="8">
            <a-form-item label="采集器" name="collector">
              <a-select
                v-model:value="queryParam.collector"
                placeholder="请选择"
                allowClear
                showSearch
                :optionFilterProp="'label'"
                :options="collectionList"
              />
            </a-form-item>
          </a-col>
          <a-col :lg="8">
            <a-form-item label="平台" name="choosePlateform">
              <j-dict-select-tag
                allowClear
                placeholder="请选择平台"
                v-model:value="choosePlateform"
                dictCode="platform"
                mode="multiple"
                @change="changeChoose"
              />
            </a-form-item>
          </a-col>
          <a-col :lg="8">
            <a-form-item label="收费" name="isVip">
              <a-select v-model:value="queryParam.isVip" placeholder="请选择是否收费" allowClear>
                <a-select-option :value="1">是</a-select-option>
                <a-select-option :value="0">否</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :lg="8">
            <a-form-item label="语言" name="languageChonsen">
              <j-dict-select-tag allowClear placeholder="请选择" ref="langRef" v-model:value="languageChonsen" dictCode="language" />
            </a-form-item>
          </a-col>
          <a-col :lg="8">
            <a-form-item label="是否签约" name="isContract">
              <a-select v-model:value="queryParam.isContract" placeholder="请选择是否签约" allowClear>
                <a-select-option :value="1">是</a-select-option>
                <a-select-option :value="0">否</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>

          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
              <a-col :lg="6">
                <a-button type="primary" preIcon="ant-design:search-outlined" @click="searchQuery">查询</a-button>
                <a-button type="primary" preIcon="ant-design:reload-outlined" @click="searchReset" style="margin-left: 8px">重置</a-button>
                <!--                <a @click="toggleSearchStatus = !toggleSearchStatus" style="margin-left: 8px">-->
                <!--                  {{ toggleSearchStatus ? '收起' : '展开' }}-->
                <!--                  <Icon :icon="toggleSearchStatus ? 'ant-design:up-outlined' : 'ant-design:down-outlined'" />-->
                <!--                </a>-->
              </a-col>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!--引用表格-->
    <BasicTable @register="registerTable" :rowSelection="rowSelection">
      <!--插槽:table标题-->
      <template #tableTitle>
        <a-button type="primary" @click="handleAdd" preIcon="ant-design:plus-outlined"> 新增</a-button>
        <!--        <a-button  type="primary" preIcon="ant-design:export-outlined" @click="onExportXls"> 导出</a-button>-->
        <j-upload-button
          type="primary"
          preIcon="ant-design:import-outlined"
          @click="onImportXls"
          @upload-success="uploadSuccess"
          @upload-loading="uploadLoading"
          >导入</j-upload-button
        >
        <a-dropdown v-if="selectedRowKeys.length > 0">
          <template #overlay>
            <a-menu>
              <a-menu-item key="1" @click="batchHandleDelete">
                <Icon icon="ant-design:delete-outlined" />
                采集
              </a-menu-item>
            </a-menu>
          </template>
          <a-button
            >批量操作
            <Icon icon="mdi:chevron-down" />
          </a-button>
        </a-dropdown>
      </template>
      <!--操作栏-->
      <template #action="{ record }">
        <TableAction
          :actions="getTableAction(record)"
          :dropDownActions="getDropDownAction(record)"
          :isUpload="true"
          :uploadData="{ bookId: record.id }"
          :uploadUrl="'/novel/book/batchImportIndex'"
          @upload-success="uploadSuccess"
          @upload-loading="uploadLoading"
        />
      </template>

      <!--字段回显插槽-->
      <template #htmlSlot="{ text }">
        <div v-html="text"></div>
      </template>
      <!--省市区字段回显插槽-->
      <template #pcaSlot="{ text }">
        {{ getAreaTextByCode(text) }}
      </template>
      <template #fileSlot="{ text }">
        <span v-if="!text" style="font-size: 12px; font-style: italic">无文件</span>
        <a-button v-else :ghost="true" type="primary" preIcon="ant-design:download-outlined" size="small" @click="downloadFile(text)">下载</a-button>
      </template>
      <template #bodyCell="{ column, record }">
        <div v-if="column.dataIndex === 'bookName'" class="text-truncate">
          <a-tooltip placement="topLeft">
            <template #title>
              <span>{{ record.bookName }}</span>
            </template>
            <div class="book-name">{{ record.bookName }}</div>
          </a-tooltip>
          <a-tooltip placement="topLeft" v-if="record.remark">
            <template #title>
              <span>{{ record.remark }}</span>
            </template>
            <Icon icon="ant-design:info-circle-outlined" style="fontsize: 20px" />
          </a-tooltip>
        </div>
      </template>
    </BasicTable>
    <!-- 表单区域 -->
    <BookIndexModal ref="registerModal" @success="handleSuccess" />
    <BookIndexShareModal ref="registerShareModal" @success="handleSuccess" />
  </div>
</template>

<script lang="ts" name="novel-bookIndex" setup>
  import { ref, reactive } from 'vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { useListPage } from '/@/hooks/system/useListPage';
  import { columns } from './BookIndex.data';
  import { list, deleteOne, batchCollection, getImportUrl, getExportUrl, removeIndex, collection, exportFun } from './BookIndex.api';
  import { downloadFile } from '/@/utils/common/renderUtils';
  import BookIndexModal from './components/BookIndexModal.vue';
  import BookIndexShareModal from './components/BookIndexShareModal.vue';
  import JSwitch from '/@/components/Form/src/jeecg/components/JSwitch.vue';
  import { defHttp } from '/@/utils/http/axios';
  import { getFileblob } from '@/api/common/api';
  import { useGlobSetting } from '/@/hooks/setting';
  import JDictSelectTag from '@/components/Form/src/jeecg/components/JDictSelectTag.vue';
  const globSetting = useGlobSetting();
  const url = ref(globSetting.uploadUrl);
  import { XLSX_FILE_SUFFIX, XLSX_MIME_TYPE } from '@/hooks/system/useMethods';
  import { message } from 'ant-design-vue';
  const formRef = ref();
  const queryParam = reactive<any>({
    bookName: '',
    authorName: '',
    lastIndexUpdateTime: '',
    createTime: '',
    catName: '',
    isAutoCollection: '',
    collectionStatus: '',
    bookStatus: '',
    collector: '',
    platforms: '',
    queryParam: '',
    language: '',
    isVip: '',
  });
  const toggleSearchStatus = ref<boolean>(false);
  const registerModal = ref();
  const registerShareModal = ref();
  const loading = ref(false);
  //注册table数据
  const { prefixCls, tableContext, onExportXls, onImportXls } = useListPage({
    tableProps: {
      title: 'book_index',
      api: list,
      columns,
      loading: loading,
      canResize: false,
      useSearchForm: false,
      actionColumn: {
        width: 160,
        fixed: 'right',
      },
      beforeFetch: (params) => {
        return Object.assign(params, queryParam);
      },
    },
    exportConfig: {
      name: 'book_index',
      url: getExportUrl,
      params: queryParam,
    },
    importConfig: {
      url: getImportUrl,
      success: handleSuccess,
    },
  });
  const [registerTable, { reload, collapseAll, updateTableDataRecord, findTableDataRecord, getDataSource }, { rowSelection, selectedRowKeys }] =
    tableContext;
  const labelCol = reactive({
    xs: { span: 24 },
    sm: { span: 7 },
  });
  const wrapperCol = reactive({
    xs: { span: 24 },
    sm: { span: 16 },
  });
  const choosePlateform = ref([]);

  const categoryList = ref();

  async function getCategoryList() {
    const data = await defHttp.get({ url: '/novel/book/category' });
    console.log(data);
    categoryList.value = data;
  }

  getCategoryList();

  const collectionList = ref();
  const langRef = ref();
  const languageChonsen = ref('');

  // 采集器下拉
  async function getCollectionList() {
    const data = await defHttp.get({ url: '/novel/book/collectionList' });
    let arr = [];
    data.forEach((item) => {
      arr.push({
        label: item.text,
        value: item.value,
      });
    });
    collectionList.value = arr;
  }

  getCollectionList();

  function uploadLoading() {
    loading.value = true;
  }

  function uploadSuccess() {
    loading.value = false;
    reload({ page: 1 });
  }

  /**
   * 新增事件
   */
  function handleAdd() {
    registerModal.value.disableSubmit = false;
    registerModal.value.add();
  }

  /**
   * 编辑事件
   */
  function handleEdit(record: Recordable) {
    registerModal.value.disableSubmit = false;
    registerModal.value.edit(record);
  }

  /**
   * 详情
   */
  function handleDetail(record: Recordable) {
    registerModal.value.disableSubmit = true;
    registerModal.value.edit(record);
  }

  /**
   * 删除事件
   */
  async function handleDelete(record) {
    await deleteOne({ id: record.id }, handleSuccess);
  }

  /**
   * 删除书籍下的所有章节
   */
  async function handleRemoveIndex(record) {
    await removeIndex({ id: record.id }, handleSuccess);
  }

  /**
   * 采集
   */
  async function handleCollection(record) {
    await collection({ bookId: record.id }, handleSuccess);
  }

  /**
   * 分享
   */
  async function handleShare(record) {
    registerShareModal.value.disableSubmit = true;
    registerShareModal.value.add(record);
  }

  /**
   * 导出
   */
  async function handleExportFun(record) {
    window.location.href = url.value + `/novel/book/export?id=${record.id}`;
    // const data=await getFileblob('/novel/book/export',{ id: record.id },)
    // if (!data.headers['content-disposition']){
    //   message.error('无可导出章节');
    //   return
    // }
    // let str=record.bookName+data.headers['content-disposition'].substr(-15)
    // let blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }); //type为所需要下载的文件格式，以xls文件为例
    //
    // let blobOptions = {type:'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'};
    //
    // //浏览器兼容，Google和火狐支持a标签的download，IE不支持
    // if (typeof window.navigator.msSaveBlob !== 'undefined') {
    //   window.navigator.msSaveBlob(new Blob([data], blobOptions), str );
    // } else {
    //   let url = window.URL.createObjectURL(new Blob([data], blobOptions));
    //   let link = document.createElement('a');
    //   link.style.display = 'none';
    //   link.href = url;
    //   link.setAttribute('download', str );
    //   document.body.appendChild(link);
    //   link.click();
    //   document.body.removeChild(link); //下载完成移除元素
    //   window.URL.revokeObjectURL(url); //释放掉blob对象
    // }
  }

  /**
   * 批量采集事件
   */
  async function batchHandleDelete() {
    await batchCollection({ ids: selectedRowKeys.value }, handleSuccess);
  }

  /**
   * 成功回调
   */
  function handleSuccess() {
    (selectedRowKeys.value = []) && reload({ page: 1 });
  }

  /**
   * 操作栏
   */
  function getTableAction(record) {
    return [
      {
        label: '编辑',
        onClick: handleEdit.bind(null, record),
      },
    ];
  }

  /**
   * 下拉操作栏
   */
  function getDropDownAction(record) {
    return [
      // {
      //   label: '详情',
      //   onClick: handleDetail.bind(null, record),
      // },
      {
        label: '删除',
        popConfirm: {
          title: '是否确认删除',
          confirm: handleDelete.bind(null, record),
        },
      },
      {
        label: '删除所有章节',
        popConfirm: {
          title: '是否确认删除',
          confirm: handleRemoveIndex.bind(null, record),
        },
      },
      {
        label: '导出',
        onClick: handleExportFun.bind(null, record),
      },
      {
        label: '分享',
        onClick: handleShare.bind(null, record),
      },
      {
        label: '采集',
        onClick: handleCollection.bind(null, record),
        ifShow: record.collectionStatus !== 2,
      },
    ];
  }

  function getLanguageLabel() {
    if (languageChonsen.value) {
      langRef.value.dictOptions.forEach((item) => {
        if (item.value == languageChonsen.value) {
          queryParam.language = item.label;
        }
      });
    } else {
      queryParam.language = '';
    }
  }

  /**
   * 查询
   */
  function searchQuery() {
    getLanguageLabel();
    reload({ page: 1 });
  }

  /**
   * 重置
   */
  function searchReset() {
    formRef.value.resetFields();
    selectedRowKeys.value = [];
    choosePlateform.value = [];
    queryParam.platforms = '';
    languageChonsen.value = '';
    getLanguageLabel();
    //刷新数据
    reload({ page: 1 });
  }
  // 改变平台
  function changeChoose(e) {
    queryParam.platforms = e.join(',');
  }
  // 采集状态改变
  function changeCollectionStatus(e) {
    queryParam.isAutoCollection = e && e != 'undefined' ? 1 : '';
  }
</script>

<style lang="less" scoped>
  .jeecg-basic-table-form-container {
    .table-page-search-submitButtons {
      display: block;
      margin-bottom: 24px;
      white-space: nowrap;
    }
    .query-group-cust {
      width: calc(50% - 15px);
      min-width: 100px !important;
    }
    .query-group-split-cust {
      width: 30px;
      display: inline-block;
      text-align: center;
    }
  }
  .text-truncate {
    display: flex;
    div {
      margin-right: 10px;
    }
    .book-name {
      width: calc(100% - 20px);
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
</style>
